package org.apmap.servlets;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;
import org.apmap.forms.LoginForm;
import org.apmap.base.User;
import org.apmap.base.Main;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LoginForm loginForm = (LoginForm) form;

        try {
            User user = findUser(loginForm);
            if (user == null) {
                request.getSession().setAttribute("error", "no user/password found");
            } else {
                request.getSession().setAttribute("user", user);
            }
        } catch (Exception e) {
            request.getSession().setAttribute("error", e.getMessage());
        }

//        return mapping.findForward("index");
        return new ActionForward(loginForm.getReturnPath(), true);
    }

    public User findUser(LoginForm loginForm) throws IllegalArgumentException {
        Session hibsession = Main.getSession();
        try {
            final Query query = hibsession.createQuery("from User where login=:login and password=:password");
            query.setString("login", loginForm.getLogin());
            query.setString("password", loginForm.getPassword());
            User user = (User) query.uniqueResult();
//            user.getAmount();
            return user;
        } finally {
            hibsession.close();
        }
    }
}